import java.util.Scanner;

public class ObserverPatternModule {
    private final Scanner scanner = new Scanner(System.in);
    private final SoilMoistureSensor soilSensor = new SoilMoistureSensor();
    private final SoilNutrientSensor nutrientSensor = new SoilNutrientSensor();
    private final WeatherSensor weatherSensor = new WeatherSensor();

    public ObserverPatternModule() {
        // 注册观察者
        IrrigationSystem irrigationSystem = new IrrigationSystem();
        soilSensor.addObserver(irrigationSystem);
        nutrientSensor.addObserver(irrigationSystem);
        weatherSensor.addObserver(irrigationSystem);
    }

    public void execute() {
        while (true) {
            System.out.println("\n===== 农田环境监测 =====");
            System.out.println("1. 设置土壤湿度");
            System.out.println("2. 查看当前土壤湿度");
            System.out.println("3. 设置土壤养分含量");
            System.out.println("4. 查看当前土壤养分含量");
            System.out.println("5. 设置气象数据");
            System.out.println("6. 查看当前气象数据");
            System.out.println("7. 返回主菜单");
            System.out.print("请选择操作(1-7): ");

            int choice = scanner.nextInt();
            scanner.nextLine();  // 消耗换行符

            switch (choice) {
                case 1 -> setSoilMoisture();
                case 2 -> viewSoilMoisture();
                case 3 -> setSoilNutrient();
                case 4 -> viewSoilNutrient();
                case 5 -> setWeatherData();
                case 6 -> viewWeatherData();
                case 7 -> { return; }
                default -> System.out.println("无效选择，请重新输入");
            }
        }
    }

    private void setSoilMoisture() {
        System.out.print("请输入土壤湿度(%): ");
        double moisture = scanner.nextDouble();
        soilSensor.setMoisture(moisture);
    }

    private void viewSoilMoisture() {
        System.out.println("当前土壤湿度: " + soilSensor.getMoisture() + "%");
    }

    private void setSoilNutrient() {
        System.out.print("请输入土壤养分含量(%): ");
        double nutrientContent = scanner.nextDouble();
        nutrientSensor.setNutrientContent(nutrientContent);
    }

    private void viewSoilNutrient() {
        System.out.println("当前土壤养分含量: " + nutrientSensor.getNutrientContent() + "%");
    }

    private void setWeatherData() {
        System.out.print("请输入温度(°C): ");
        double temperature = scanner.nextDouble();
        System.out.print("请输入湿度(%): ");
        double humidity = scanner.nextDouble();
        System.out.print("请输入风速(m/s): ");
        double windSpeed = scanner.nextDouble();
        weatherSensor.setWeatherData(temperature, humidity, windSpeed);
    }

    private void viewWeatherData() {
        System.out.println("当前温度: " + weatherSensor.getTemperature() + "°C");
        System.out.println("当前湿度: " + weatherSensor.getHumidity() + "%");
        System.out.println("当前风速: " + weatherSensor.getWindSpeed() + "m/s");
    }
}